import * as THREE from "three"
import { CSS3DObject, CSS3DRenderer } from "three/addons/Addons.js";

export class OccludeHtml {

    /** @type {CSS3DRenderer} */
    renderer

    constructor() {

        const renderer = new CSS3DRenderer();
        renderer.domElement.style.position = 'absolute';
        renderer.domElement.style.top = 0;
        this.renderer = renderer

        document.getElementById('sketch_three_canvas').insertAdjacentElement("afterbegin", renderer.domElement);

        this.collection = []

    }

    /**
     * 创建自定义 HTMLDivElement
     * @returns { HTMLDivElement }
     */
    createDiv() {

        return document.createElement("custom-div");

    }

    /**
     * 创建Object3D
     * @param {CustomDivElement} element 
     * @param { "CSS2DObject"|"CSS3DObject" } type 
     */
    createObject3D(element, type = "CSS3DObject") {

        const el_obj3d = element.object3d

        if (el_obj3d) {

            const css3d = new CSS3DObject(element)

            el_obj3d.add(css3d)

            el_obj3d.customType = type === "CSS2DObject" ? "CSS2DObject" : "CSS3DObject"

            this.collection.push(el_obj3d)

            return el_obj3d

        } else {

            return console.warn("please create a custom div with `OccludeHtml.createDiv`");

        }


    }



    /**
     * render
     * @param {THREE.Scene} scene 
     * @param {THREE.Camera} camera 
     */
    render = (scene, camera) => {

        this.renderer.render(scene, camera)

    }

    onCameraChanged(camera, controls) {

        const direction = new THREE.Vector3().subVectors(camera.position, controls.target).normalize()

        this.collection.forEach(item => {

            if (item.customType === "CSS2DObject") {

                // 计算 CSS3DObject 的大小，使之保持远近一样大
                const distance = camera.position.distanceTo(item.position)

                const scale = distance / __distance

                item.scale.set(scale, scale, scale)

                // 计算 CSS3DObject 的朝向，使之始终朝向屏幕
                const lookAt = item.getWorldPosition(new THREE.Vector3()).add(direction)

                item.lookAt(lookAt)

            }

        })
    }

}


export class CustomDivElement extends HTMLElement {

    object3d = new THREE.Object3D()

    constructor() {

        super()

    }

    connectedCallback() {

        console.log("自定义元素加入页面")

        // 创建平面
        const width = this.clientWidth
        const height = this.clientHeight
        const geometry = new THREE.BoxGeometry(width, height, 1)

        // 剩余逻辑，相同 ......

        this.__update()

    }

    disconnectedCallback() {

        console.log("自定义元素从页面移除")

    }

    adoptedCallback() {

        console.log("自定义元素转移到新页面")

    }

    attributeChangedCallback(name, oldValue, newValue) {

        console.log("自定义元素属性发生变化")

        this.__update()

    }

    __update() {

        // update

    }

}

customElements.define("custom-div", CustomDivElement)